package markov;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class POSBigram {
    ArrayList<String[]> arr;
    HashMap<String, HashMap<String,Integer>> posCount;
    public HashMap<String, HashMap<String,Double>> posProbability;
    public HashMap<String, HashMap<String,Double>> posProbabilityChildIndex; 
    HashMap<String, Integer> posTotal;
    public Boolean PRING_DEBUG_INFO;
    public POSBigram(ArrayList<String[]> arr){
	this.arr = arr;
	posCount = new HashMap<String, HashMap<String,Integer>>();
	posProbability = new HashMap<String, HashMap<String,Double>>();
	posTotal = new HashMap<String, Integer>();
	PRING_DEBUG_INFO = false;
	posProbabilityChildIndex = new HashMap<String, HashMap<String,Double>>();
    }

    public void run(){
	String [] prev = null;
	for( String[] cur : arr){

	    if(prev == null){ //skip first one
		prev = cur;
		continue;
	    }


	    if(posTotal.containsKey(prev[1]))
		posTotal.put(prev[1], posTotal.get(prev[1])+1); //increment total count
	    else
		posTotal.put(prev[1], 1);

	    if(posCount.containsKey(prev[1])){ //word
		//TODO contains type key
		int val = 0;

		if(posCount.get(prev[1]).containsKey(cur[1]))
		    val = posCount.get(prev[1]).get(cur[1]);
		else
		    posCount.get(prev[1]).put(cur[1], 1);
		posCount.get(prev[1]).put(cur[1], ++val);
	    }else{
		final String tmp = cur[1];
		posCount.put(prev[1], new HashMap<String, Integer>(){{put(tmp ,1);}});
	    }
	    prev = cur;
	}
	
	generateProbability();
	if(PRING_DEBUG_INFO) printCount();
    }
    public void generateProbability(){
	for(final Map.Entry<String, HashMap<String,Integer>> a : posCount.entrySet()){
	    for(final Map.Entry<String,Integer> b : a.getValue().entrySet()){
		final double prob = b.getValue() / (double) posTotal.get(a.getKey());
		if(posProbability.containsKey(a.getKey())){
		    posProbability.get(a.getKey()).put(b.getKey(), prob);
		}
		else
		    posProbability.put(a.getKey(), new HashMap(){{put(b.getKey(),prob);}});		
		//posProbabilityChildIndex.put(b.getKey(), new HashMap(){{put(a.getKey(),prob);}});
	    }
	}
    }
    public void printCount(){
	
	/*for(Map.Entry<String, HashMap<String,Integer>> pos1 : posCount.entrySet()){
	    for(Map.Entry<String,Integer> pos2 : pos1.getValue().entrySet()){
		
		System.out.println(pos1.getKey() + "\t" + pos2.getKey() + "\t" + (pos2.getValue()) + "\t/" + posTotal.get(pos1.getKey()) + "\t=" + ((pos2.getValue())/(double)posTotal.get(pos1.getKey()) ));
	    }
	    
	}*/
	
	for(Map.Entry<String, HashMap<String,Double>> pos1 : posProbability.entrySet()){
	    for(Map.Entry<String,Double> pos2 : pos1.getValue().entrySet()){
		
		System.out.println(pos1.getKey() + "\t" + pos2.getKey() + "\t" + (pos2.getValue()) + "\t/" + posTotal.get(pos1.getKey()));
	    }
	    
	}
    }

}
